import request from "@/api/request.js"
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
//文件夹名称
const getDateFolder = () => {
  const t = new Date()
  let timeStr = ''
  timeStr = timeStr + t.getFullYear() //年
  timeStr = timeStr + (t.getMonth() + 1) //月，因为从0开始，所以需要加1
  timeStr = timeStr + t.getDate() //日
  return timeStr
}
const uploadFileToOss = (filePath) => {
  return new Promise((resolve,reject) => {
    //获取签名
    request({
      url: '/oss/sts',
      method: 'get',
	  no_loading: true
    })
    .then(res => {
      const {access_key_secret,access_key_id,security_token,signature,policy} = res
	  console.log(signature,"这是")
      const key = getDateFolder() + '/' + new Date().getTime() + '_' + filePath.split(":")[1]
      const url = 'https://appwetools.oss-cn-hangzhou.aliyuncs.com'
      wx.uploadFile({
        filePath,
        name: "file",
        url: url,
        formData: {
          host: "appwetools.oss-cn-hangzhou.aliyuncs.com",
          key: key,
          ossAccessKeyId: access_key_id,
          signature: signature,
          policy: policy,
          "x-oss-security-token": security_token
        },
        success: (res) => {
          if (res.statusCode === 204) {
            resolve(url+'/'+key)
          }else{
            reject()
          }
        },
        fail: err => {
          console.log(err);
          reject()
        }
      })
    })
    
  })
}
module.exports = {
  formatTime,
  uploadFileToOss
}
